package com.imist.nettybasic4.client.handler;

import com.imist.nettybasic4.protocol.request.LoginRequestPacket;
import com.imist.nettybasic4.protocol.response.LoginResponsePacket;
import com.imist.nettybasic4.session.Session;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.UUID;


public class LoginResponseHandler extends SimpleChannelInboundHandler<LoginResponsePacket> {
    /**
     * 客户端连接成功之后调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //创建登陆对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUsername("iMisty");
        loginRequestPacket.setPassword("123456");
        //发送登录请求包.这里从控制台登录
        //ctx.channel().writeAndFlush(loginRequestPacket);
        //ctx.fireChannelActive();
        super.channelActive(ctx);
    }


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginResponsePacket loginResponsePacket) throws Exception {
        String userId =loginResponsePacket.getUserId();
        String userName =loginResponsePacket.getUserName();
        if (loginResponsePacket.isSuccess()){
            SessionUtils.bindSession(new Session(userId,userName),channelHandlerContext.channel());
            System.out.println("["+userName+"] 登录成功，userId为： "+loginResponsePacket.getUserId()  );
        }else {
            System.out.println(new Date()+" : 客户端登陆失败...原因是:"+loginResponsePacket.getReason());
        }
    }
}
